package com.hxh.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/9/6 21:11
 * 使用 lock 实现四个线程分别进行 +1 -1 +1 -1的操作
 * 线程通信, 注意虚假唤醒问题
 */
public class ThreadDemo02 {

    public static void main(String[] args) {
        LShare share = new LShare();
        new Thread(() -> {
           while (true) {
               try {
                   share.incr();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        }, "AA").start();

        new Thread(() -> {
            while (true) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();

        new Thread(() -> {
            while (true) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC").start();

        new Thread(() -> {
            while (true) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }
}

// 资源类
class LShare {

    private int num = 0;

    // 可重入锁
    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    // +1
    public void incr() throws InterruptedException {
        lock.lock();
        try {
            while (num != 0) {
                condition.await(); // 等待
            }
            num++;
            System.out.println(Thread.currentThread().getName() + "::" + num);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    // -1
    public void decr() throws InterruptedException {
        lock.lock();
        try {
            while (num != 1) {
                condition.await(); // 等待
            }
            num--;
            System.out.println(Thread.currentThread().getName() + "::" + num);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
